package com.ywj.client;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.UUID;

public class WSHeartBeatRunnable implements Runnable{
//    public static Logger logger = LoggerFactory.getLogger(WSHeartBeatRunnable.class);
    @Override
    public void run() {
        System.out.println("进入WSHeartBeatRunnable的run方法");
//        logger.info("进入WSHeartBeatRunnable的run方法");
        while (true){
            Session session = WebSocketClientHeartBeat.session;
            if(session != null){
//                logger.info("当前WSHeartBeatRunnable的session为： {}", session.getId());
                System.out.println("当前WSHeartBeatRunnable的session为： " + session.getId());
                JSONObject heartJSONObject = new JSONObject();
                heartJSONObject.put("id", "MSG_HEARTBEAT");
                heartJSONObject.put("msgId", UUID.randomUUID().toString());
                try{
                    session.getBasicRemote().sendText(JSONObject.toJSONString(heartJSONObject));
                    System.out.println("客户端成功发送WebSocket心跳消息");
//                    logger.info("客户端成功发送WebSocket心跳消息");
                    Thread.sleep(10000);
                } catch (Exception e) {
                    System.out.println("WebSocket发送心跳消息异常，" + e);
//                    logger.info("WebSocket发送心跳消息异常，{}", e);
                    //之前服务端离线 后在线。session非空 但心跳一直发送异常
                    WebSocketClientHeartBeat.reConnect();
                    try {
//                        Thread.sleep(600000);
                        Thread.sleep(60000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
            else{
//                WebSocketClientHeartBeat.reConnect();
                //websocket未连接的话 休眠5s
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }




        }
    }
}

